package com.abbcc.module.user;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.abbcc.action.BaseAction;
import com.abbcc.common.CommonConst;
import com.abbcc.models.TdUser;
import com.abbcc.service.UserService;
import com.abbcc.util.StringUtil;

public class UserAction extends BaseAction<TdUser>{
	@Autowired
	private UserService userService;
	public String loginType;
	public String oldPsw;
	public String login(){
		if(StringUtil.isNotBlank(entity.getUsername())&&StringUtil.isNotBlank(entity.getPassword())){
			TdUser td = new TdUser();
			td.setUsername(entity.getUsername());
			td.setPassword(entity.getPassword());
			List<TdUser> temp = userService.findByExample(td);
			if(temp.size()==0){
				result = "用户名或密码错误!";
				loginType = "user";
				return INPUT;
			}
			getSession().setAttribute(CommonConst.SESSIONUSER, temp.get(0));
		}else{
			loginType = "user";
			result = "用户名或密码不能为空";
			return INPUT;
		}
		getCurrentUser().setLoginTime(new Date());
		userService.update(getCurrentUser());
		return SUCCESS;
	}
	public String loginout() {
		if (getCurrentAdmin() != null)
			saveLog(entity.getUsername(), "退出成功!", CommonConst.LOGLOGOUT,
					CommonConst.LOGTYPEBYADMIN);
		this.getSession().invalidate();
		loginType = "user";
		return INPUT;
	}

	public String updatePsw() {
		if (StringUtil.isNotBlank(oldPsw)
				&& StringUtil.isNotBlank(entity.getPassword())) {
			if (oldPsw.equals(getCurrentUser().getPassword())) {
				getCurrentUser().setPassword(entity.getPassword());
				userService.saveOrUpdate(getCurrentUser());
				reloadSession(CommonConst.SESSIONUSER, getCurrentUser());
				result = "修改成功!";
				saveLog("密码", result, CommonConst.LOGUPDATE,
						CommonConst.LOGTYPEBYUSER);
			} else {
				result = "原密码不正确";
				saveLog("密码", result, CommonConst.LOGUPDATE,
						CommonConst.LOGTYPEBYUSER);
			}
		}
		return JSON;
	}
	public String getLoginType() {
		return loginType;
	}
	public void setLoginType(String loginType) {
		this.loginType = loginType;
	}
	
}
